package cn.damai.search.service.impl;

import cn.damai.common.*;
import cn.damai.model.*;
import cn.damai.search.baseService.*;
import cn.damai.search.service.TestService;
import cn.damai.search.vo.*;
import cn.damai.util.DubboUtil;
import com.alibaba.dubbo.config.annotation.Service;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.text.ParseException;
import java.util.*;

/**
 * 具体项目实现
 */
@Component
@Service(version = DubboUtil.VRESION,group = DubboUtil.GROUP)
public class TestServiceIpml implements TestService {

    @Autowired
    private BaseItemService itemService;
    @Autowired
    private BaseImageService imageService;
    @Autowired
    private BaseCinemaService cinemaService;
    @Autowired
    private BaseSchedulerService schedulerService;
    @Autowired
    private BaseSchedulerSeatPriceService schedulerSeatPriceService;
    @Autowired
    private BaseSchedulerSeatService schedulerSeatService;
    @Autowired
    private BaseUserService userService;



    //测试接口 1 ok 首页5张轮播图
    @Override
    public List<HotItemVo> queryBanner() {
        //查询轮播图前5个
        Map<String,Object> param = new HashMap<>();
        param.put("isBanner",1);
        param.put("beginPos",0);
        param.put("pageSize",5);
        List<Item> ItemList = itemService.getItemListByMap(param);
        //组装接口返回数据
        List<HotItemVo> hotItemVoList = new ArrayList<>();
        if (EmptyUtils.isEmpty(ItemList)){
            return null;
        }
        for (Item Item:ItemList){
            HotItemVo hotItemVo = new HotItemVo();
            BeanUtils.copyProperties(Item,hotItemVo);
            //查询图片信息
            List<Image> ImageList = imageService.queryImageList(Item.getId(),
                    Constants.Image.ImageType.carousel,
                    Constants.Image.ImageCategory.item);
            //组装图片信息
            hotItemVo.setImgUrl(EmptyUtils.isEmpty(ImageList)? null:ImageList.get(0).getImgUrl());
            hotItemVoList.add(hotItemVo);
        }
        return hotItemVoList;
    }

    //商品详情 - 测试 ok
    @Override
    public Dto<ItemDetailVo> queryItemDetail(Long id) {
        Item Item = itemService.getItemById(id);
        if(EmptyUtils.isEmpty(Item)){
            System.out.println("我进来过");
            return null;
        }
        //查询图片
        List<Image> ImagesList = getimageList(Item.getId(), Constants.Image.ImageType.carousel, Constants.Image.ImageCategory.item);
        //查询剧院
        Cinema Cinema = cinemaService.getCinemaById(Item.getCinemaId());
        //组装返回数据
        ItemDetailVo itemDetailVo = copyData(Item,Cinema,ImagesList);

        return DtoUtil.returnDataSuccess(itemDetailVo);
    }

    //商品排期 - 测试 ok
    @Override
    public Dto<List<ItemSchedulerVo>> queryItemScheduler(Long id) {
        //根据商品主键查询商品信息
        Item Item = itemService.getItemById(id);
        if(EmptyUtils.isEmpty(Item)){
            return null;
        }
        //查询对应的排期列表
        Map<String,Object> param = new HashMap<String,Object>();
        param.put("itemId",Item.getId());
        List<Scheduler> SchedulerList = schedulerService.getSchedulerListByMap(param);
        if(EmptyUtils.isEmpty(SchedulerList)){
            return null;
        }
        //组装返回数组
        List<ItemSchedulerVo> itemSchedulerVoList = new ArrayList<ItemSchedulerVo>();
        for (int i = 0; i < SchedulerList.size(); i++) {
            ItemSchedulerVo itemSchedulerVo = new ItemSchedulerVo();
            BeanUtils.copyProperties(Item,itemSchedulerVo);
            BeanUtils.copyProperties(SchedulerList.get(i),itemSchedulerVo);
            //更新显示字段-时间字段
            try {
                itemSchedulerVo.setStartTime(DateUtil.format(SchedulerList.get(i).getStartTime()));
                itemSchedulerVo.setEndTime(DateUtil.format(SchedulerList.get(i).getEndTime()));
            } catch (ParseException e) {
                e.printStackTrace();
            }
            itemSchedulerVoList.add(itemSchedulerVo);

        }
        return DtoUtil.returnDataSuccess(itemSchedulerVoList);
    }

    //更具排期id查询价格 ok
    @Override
    public Dto<List<ItemPriceVo>> queryItemPrice(Long id) {
        Map<String,Object> param = new HashMap<String,Object>();
        param.put("scheduleId",id);
        //根据排期id查询排期价格信息
        List<SchedulerSeatPrice> SchedulerSeatPriceList = schedulerSeatPriceService.getSchedulerSeatPriceListByMap(param);
        if (EmptyUtils.isEmpty(SchedulerSeatPriceList)) {
            return null;
        }
        //组装返回显示信息
        List<ItemPriceVo> itemPriceVoList = new ArrayList<ItemPriceVo>();
        for (SchedulerSeatPrice SchedulerSeatPrice : SchedulerSeatPriceList){
            ItemPriceVo itemPriceVo = new ItemPriceVo();
            BeanUtils.copyProperties(SchedulerSeatPrice,itemPriceVo);
            //查询所有是有效座位并且没有被锁定的座位
            Map<String,Object> lockMap = new HashMap<String,Object>();
            lockMap.put("status",1);
            lockMap.put("scheduleId",itemPriceVo.getScheduleId());
            int num = schedulerSeatService.getSchedulerSeatCountByMap(lockMap);
            int isHaveSeat = num > 0 ? 1:0;
            itemPriceVo.setIsHaveSeat(isHaveSeat);
            itemPriceVoList.add(itemPriceVo);
        }
        return DtoUtil.returnDataSuccess(itemPriceVoList);
    }


    //测试  账号密码登陆
    @Override
    public Object[] login(User dmUser) {
        //验证用户登陆是否成功
      User user = userService.checkloginByPassword(dmUser);
        if (EmptyUtils.isEmpty(user)) {
            return null;
        }
        //组装信息
        UserVO userVo = new UserVO();
        BeanUtils.copyProperties(user,userVo);
        userVo.setUserId(user.getId());
        //更新用户头像
        List<Image> imagesList = imageService.queryImageList(user.getId(),
                Constants.Image.ImageType.normal,
                Constants.Image.ImageCategory.user);
        if (EmptyUtils.isNotEmpty(imagesList)) {
            userVo.setImageId(imagesList.get(0).getId());
            userVo.setImgUrl(imagesList.get(0).getImgUrl());
        }
        //生成用户token
        String token = this.generateToken(user);
        //保存token到redis中
        //this.saveToken(token,userVo);
        System.out.println(token.toString()+"\n"+userVo.getPhone());

        TokenVO tokenVo = new TokenVO(token,Constants.Redis_Expire.SESSION_TIMEOUT,new Date().getTime());
        return new Object[]{userVo,tokenVo};
    }
        //此方法  需要 redis 登陆比较重要的方法 需要改
//    private void saveToken(String token, UserVO userVo) {
//        String tokenKey = Constants.USER_TOKEN_PREFIX + userVo.getUserId();
//        String tokenValue = null;
//        //检查是否已经登陆,如果还在登陆 有效期内,就需要删除掉原来的登陆信息
//        if((tokenValue = redisUtils.get(tokenKey)) != null){
//            //代表原来用户已经登陆
//            redisUtils.delete(tokenKey);
//        }
//        //缓存用户token
//        redisUtils.set(tokenKey,Constants.Redis_Expire.SESSION_TIMEOUT,token);
//        //缓存用户详细信息
//        redisUtils.set(token,Constants.Redis_Expire.SESSION_TIMEOUT,JSON.toJSONString(userVo));
//    }

    private String generateToken(User user) {
        return userService.generateToken(user);
    }


    //粘贴数据方法  商品详情 组装返回信息用
    private ItemDetailVo copyData(Item Item, Cinema Cinema, List<Image> ImagesList) {

        ItemDetailVo itemDetailVo = new ItemDetailVo();
        BeanUtils.copyProperties(Item,itemDetailVo);
        try {
            itemDetailVo.setStartTime(DateUtil.format(Item.getStartTime()));
            itemDetailVo.setEndTime(DateUtil.format(Item.getEndTime()));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        itemDetailVo.setState(Item.getState()+"");
        itemDetailVo.setImgUrl(ImagesList.get(0).getImgUrl());
        if(EmptyUtils.isEmpty(Cinema)){
            BeanUtils.copyProperties(Cinema,itemDetailVo);
        }
        itemDetailVo.setId(Item.getId());
        return itemDetailVo;
    }

    /***
     * 查询图片
     */
    public List<Image> getimageList(Long id,Integer type,Integer category){
        Map<String,Object> paramImage = new HashMap<>();
        paramImage.put("targetId",id);
        paramImage.put("type",type);
        paramImage.put("category",category);
        return imageService.queryImageList(id,type,category);
    }
}
